import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import '../model/difficulty.dart';
import 'level_select_page.dart';
import 'how_to_play_page.dart';

// 自定义路由类，支持iOS侧滑返回
class _SlidePageRoute<T> extends PageRouteBuilder<T> {
  final Widget page;

  _SlidePageRoute({required this.page})
    : super(
        pageBuilder: (context, animation, secondaryAnimation) => page,
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          // 主页面滑动动画
          final slideAnimation =
              Tween<Offset>(
                begin: const Offset(1.0, 0.0), // 从右侧滑入
                end: Offset.zero,
              ).animate(
                CurvedAnimation(parent: animation, curve: Curves.easeOutCubic),
              );

          // 当前页面退出动画
          final exitSlideAnimation =
              Tween<Offset>(
                begin: Offset.zero,
                end: const Offset(-0.3, 0.0), // 向左滑出
              ).animate(
                CurvedAnimation(
                  parent: secondaryAnimation,
                  curve: Curves.easeInCubic,
                ),
              );

          return Stack(
            children: [
              // 当前页面退出效果
              SlideTransition(
                position: exitSlideAnimation,
                child: Container(), // 这里会被当前页面替换
              ),

              // 新页面进入效果
              SlideTransition(position: slideAnimation, child: child),
            ],
          );
        },
        transitionDuration: const Duration(milliseconds: 300),
        reverseTransitionDuration: const Duration(milliseconds: 300),
      );

  @override
  bool get canPop => true;

  @override
  bool get popGestureEnabled => true; // 启用侧滑返回手势
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  late List<AnimationController> _cardAnimationControllers;
  late List<Animation<double>> _cardAnimations;
  late List<Animation<Offset>> _cardSlideAnimations;

  @override
  void initState() {
    super.initState();

    // 主动画控制器
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    // 淡入动画
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
      ),
    );

    // 滑动动画
    _slideAnimation =
        Tween<Offset>(begin: const Offset(0, 0.3), end: Offset.zero).animate(
          CurvedAnimation(
            parent: _animationController,
            curve: const Interval(0.0, 0.8, curve: Curves.easeOutCubic),
          ),
        );

    // 卡片动画控制器
    _cardAnimationControllers = List.generate(6, (index) {
      return AnimationController(
        duration: Duration(milliseconds: 600 + (index * 100)),
        vsync: this,
      );
    });

    // 卡片动画
    _cardAnimations = _cardAnimationControllers.map((controller) {
      return Tween<double>(
        begin: 0.0,
        end: 1.0,
      ).animate(CurvedAnimation(parent: controller, curve: Curves.easeOutBack));
    }).toList();

    // 卡片滑动动画
    _cardSlideAnimations = _cardAnimationControllers.map((controller) {
      return Tween<Offset>(
        begin: const Offset(1.0, 0),
        end: Offset.zero,
      ).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeOutCubic),
      );
    }).toList();

    // 启动动画
    _startAnimations();
  }

  void _startAnimations() async {
    _animationController.forward();

    // 延迟启动卡片动画
    await Future.delayed(const Duration(milliseconds: 300));
    for (int i = 0; i < _cardAnimationControllers.length; i++) {
      await Future.delayed(const Duration(milliseconds: 80));
      if (mounted) {
        _cardAnimationControllers[i].forward();
      }
    }
  }

  // 刷新动画
  Future<void> _refreshAnimations() async {
    // 重置所有动画
    _animationController.reset();
    for (var controller in _cardAnimationControllers) {
      controller.reset();
    }

    // 重新启动动画
    await Future.delayed(const Duration(milliseconds: 200));
    _startAnimations();
  }

  @override
  void dispose() {
    _animationController.dispose();
    for (var controller in _cardAnimationControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      extendBody: true, // 让body延伸到底部
      backgroundColor: Colors.transparent, // 设置透明背景
      appBar: AppBar(
        title: const Text(
          '修炼手册',
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
        centerTitle: true,
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: isDark
                ? [
                    const Color(0xFF121212),
                    const Color(0xFF1E1E1E),
                    const Color(0xFF1E1E1E), // 延伸到底部
                  ]
                : [
                    const Color(0xFFF1F8E9),
                    const Color(0xFFE8F5E8),
                    const Color(0xFFE8F5E8), // 延伸到底部
                  ],
            stops: const [0.0, 0.8, 1.0], // 控制渐变停止点
          ),
        ),
        child: RefreshIndicator(
          onRefresh: _refreshAnimations,
          color: isDark ? const Color(0xFF4CAF50) : const Color(0xFF2E7D32),
          backgroundColor: isDark ? const Color(0xFF2D2D2D) : Colors.white,
          child: SafeArea(
            bottom: false, // 不在底部添加安全区域，让内容延伸到小白条
            child: Padding(
              padding: const EdgeInsets.fromLTRB(
                20.0,
                20.0,
                20.0,
                0.0,
              ), // 底部不添加padding
              child: SingleChildScrollView(
                physics: const BouncingScrollPhysics(),
                padding: EdgeInsets.only(
                  bottom:
                      MediaQuery.of(context).padding.bottom + 20, // 为小白条留出空间
                ),
                child: Column(
                  children: [
                    // 标题区域 - 现在在滚动视图内部
                    SlideTransition(
                      position: _slideAnimation,
                      child: FadeTransition(
                        opacity: _fadeAnimation,
                        child: Container(
                          margin: const EdgeInsets.only(bottom: 40, top: 20),
                          child: Column(
                            children: [
                              Icon(
                                Icons.auto_awesome,
                                size: 60,
                                color: isDark
                                    ? const Color(0xFF4CAF50)
                                    : const Color(0xFF2E7D32),
                              ),
                              const SizedBox(height: 16),
                              Text(
                                '选择修炼境界',
                                style: TextStyle(
                                  fontSize: 28,
                                  fontWeight: FontWeight.bold,
                                  color: isDark
                                      ? Colors.white
                                      : const Color(0xFF1B5E20),
                                ),
                              ),
                              const SizedBox(height: 8),
                              Text(
                                '踏上数独修炼之路',
                                style: TextStyle(
                                  fontSize: 16,
                                  color: isDark
                                      ? Colors.white70
                                      : const Color(0xFF4CAF50),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),

                    // 难度选择区域
                    _buildAnimatedDifficultyCard(
                      context,
                      0,
                      '炼气期',
                      '初入修炼，基础入门',
                      Icons.eco,
                      Difficulty.easy,
                      const Color(0xFF81C784),
                    ),
                    _buildAnimatedDifficultyCard(
                      context,
                      1,
                      '筑基期',
                      '稳固根基，渐入佳境',
                      Icons.foundation,
                      Difficulty.medium,
                      const Color(0xFF66BB6A),
                    ),
                    _buildAnimatedDifficultyCard(
                      context,
                      2,
                      '结丹期',
                      '凝聚精华，小有成就',
                      Icons.circle,
                      Difficulty.hard,
                      const Color(0xFF4CAF50),
                    ),
                    _buildAnimatedDifficultyCard(
                      context,
                      3,
                      '元婴期',
                      '神识初现，境界提升',
                      Icons.psychology,
                      Difficulty.high,
                      const Color(0xFF388E3C),
                    ),
                    _buildAnimatedDifficultyCard(
                      context,
                      4,
                      '化神期',
                      '神通广大，登峰造极',
                      Icons.auto_awesome,
                      Difficulty.superHigh,
                      const Color(0xFF2E7D32),
                    ),

                    const SizedBox(height: 20),

                    // 修炼说明按钮
                    SlideTransition(
                      position: _cardSlideAnimations[5],
                      child: ScaleTransition(
                        scale: _cardAnimations[5],
                        child: Container(
                          width: double.infinity,
                          margin: const EdgeInsets.symmetric(horizontal: 20),
                          child: OutlinedButton.icon(
                            onPressed: () => Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (_) => HowToPlayPage(),
                              ),
                            ).then((_) => setState(() {})),
                            icon: const Icon(Icons.help_outline),
                            label: const Text('修炼说明'),
                            style: OutlinedButton.styleFrom(
                              foregroundColor: isDark
                                  ? const Color(0xFF4CAF50)
                                  : const Color(0xFF2E7D32),
                              side: BorderSide(
                                color: isDark
                                    ? const Color(0xFF4CAF50)
                                    : const Color(0xFF2E7D32),
                                width: 2,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(16),
                              ),
                              padding: const EdgeInsets.symmetric(
                                vertical: 16,
                                horizontal: 24,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 带动画的难度卡片
  Widget _buildAnimatedDifficultyCard(
    BuildContext context,
    int index,
    String title,
    String subtitle,
    IconData icon,
    Difficulty difficulty,
    Color color,
  ) {
    return SlideTransition(
      position: _cardSlideAnimations[index],
      child: ScaleTransition(
        scale: _cardAnimations[index],
        child: _buildDifficultyCard(
          context,
          title,
          subtitle,
          icon,
          difficulty,
          color,
        ),
      ),
    );
  }

  Widget _buildDifficultyCard(
    BuildContext context,
    String title,
    String subtitle,
    IconData icon,
    Difficulty difficulty,
    Color color,
  ) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return TweenAnimationBuilder<double>(
      duration: const Duration(milliseconds: 200),
      tween: Tween<double>(begin: 1.0, end: 1.0),
      builder: (context, scale, child) {
        return Transform.scale(
          scale: scale,
          child: Container(
            width: double.infinity,
            margin: const EdgeInsets.only(bottom: 16),
            child: Card(
              elevation: 8,
              shadowColor: Colors.black26,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              color: isDark ? const Color(0xFF2D2D2D) : Colors.white,
              child: InkWell(
                borderRadius: BorderRadius.circular(20),
                onTap: () async {
                  // 添加触觉反馈
                  HapticFeedback.lightImpact();

                  // 延迟一点时间让用户感受到点击反馈
                  await Future.delayed(const Duration(milliseconds: 50));

                  // 检查widget是否仍然mounted
                  if (context.mounted) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (_) => LevelSelectPage(difficulty: difficulty),
                      ),
                    ).then((_) => setState(() {}));
                  }
                },
                // 添加更好的视觉反馈
                splashColor: color.withValues(alpha: 0.3),
                highlightColor: color.withValues(alpha: 0.1),
                child: Padding(
                  padding: const EdgeInsets.all(20),
                  child: Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: isDark
                              ? color.withValues(alpha: 0.3)
                              : color.withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: Icon(
                          icon,
                          size: 32,
                          color: isDark ? color.withValues(alpha: 0.9) : color,
                        ),
                      ),
                      const SizedBox(width: 20),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              title,
                              style: TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                                color: isDark
                                    ? Colors.white
                                    : const Color(0xFF1B5E20),
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              subtitle,
                              style: TextStyle(
                                fontSize: 14,
                                color: isDark
                                    ? Colors.white70
                                    : const Color(0xFF4CAF50),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: isDark
                            ? Colors.white54
                            : const Color(0xFF4CAF50),
                        size: 20,
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
